package de.wohlgemuth.checksize;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	 String dwnload_file_path = "http://wohlgemuth-team.de/messe.xml";
	    String dest_file_path = "/sdcard/messe.xml";
	    Button b1;
	    ProgressDialog dialog = null;
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	         
	        b1 = (Button)findViewById(R.id.Button01);
	        b1.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                 
	                dialog = ProgressDialog.show(MainActivity.this, "", "Downloading file...", true);
	                 new Thread(new Runnable() {
	                        public void run() {
	                             downloadFile(dwnload_file_path, dest_file_path);
	                        }
	                      }).start();               
	            }
	        });
	    }
	     
	    public void downloadFile(String url, String dest_file_path) {
	          try {
	              File dest_file = new File(dest_file_path);
	              URL u = new URL(url);
	              URLConnection conn = u.openConnection();
	              int contentLength = conn.getContentLength();
	              DataInputStream stream = new DataInputStream(u.openStream());
	              byte[] buffer = new byte[contentLength];
	              stream.readFully(buffer);
	              stream.close();
	              DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
	              fos.write(buffer);
	              fos.flush();
	              fos.close();
	              hideProgressIndicator();
	               
	          } catch(FileNotFoundException e) {
	              hideProgressIndicator();
	              return; 
	          } catch (IOException e) {
	              hideProgressIndicator();
	              return; 
	          }
	    }
	     
	    void hideProgressIndicator(){
	        runOnUiThread(new Runnable() {
	            public void run() {
	                dialog.dismiss();
	            }
	        });  
	    }

		
	}

